package com.initialize.core.filter.head;

import com.initialize.commom.config.header.HeaderConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;
import redis.clients.jedis.Jedis;

/**
 * Created with IntelliJ IDEA.
 * User: jane
 * Date: 2019/12/29
 * Time: 10:24 下午
 * Description: 拦截外部访问
 */
@Slf4j
@Component
public class InternalWebRequestInterceptor implements WebRequestInterceptor {

    final
    Jedis jedis;

    public InternalWebRequestInterceptor(Jedis jedis) {
        this.jedis = jedis;
    }

    @Override
    public void preHandle(WebRequest request) throws Exception {
        String header = request.getHeader(HeaderConfig.INTERNAL_SECRET_KEY);
        if (header == null || header.isEmpty()) {
            throw new Exception("未携带内部令牌");
        } else {
            if (!jedis.sismember(HeaderConfig.INTERNAL_SECRET_KEY, header)) {
                throw new Exception("非法的内部令牌");
            }
            //销毁令牌
            jedis.srem(HeaderConfig.INTERNAL_SECRET_KEY, header);
        }

    }

    @Override
    public void postHandle(WebRequest request, ModelMap model) throws Exception {

    }

    @Override
    public void afterCompletion(WebRequest request, Exception ex) throws Exception {

    }


}